<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Http\Requests\Setting\MenuStoreRequest;
use App\Models\Menu;

class MenuController extends Controller
{
    public function index(): array
    {
        $list = Menu::query()->get()->toArray();
        return $this->success(data: $list);
    }

    public function detail(int $id): array
    {
        $menu = Menu::query()->find($id)->toArray();
        if ($menu['type'] === 2) {
            $menu['btns'] = Menu::query()->where('pid', $id)->get()->toArray();
        }
        return $this->success(data: $menu);
    }

    public function store(MenuStoreRequest $request): array
    {
        $params = $request->validated();
        $this->checkParams($params);

        $btns = $params['btns'] ?? [];
        unset($params['btns']);

        $id = Menu::query()->insertGetId($params);
        $this->updateBtns($id, $btns);
        return $this->success(data: ['id' => $id]);
    }


    public function update(int $id, MenuStoreRequest $request)
    {
        $params = $request->validated();
        $this->checkParams($params);

        $btns = $params['btns'] ?? [];
        unset($params['btns']);

        $this->updateBtns($id, $btns);
        Menu::query()->where('id', $id)->update($params);
        return $this->success();
    }

    public function destroy()
    {

    }

    protected function updateBtns(int $id, array $btns): void
    {
        if ($btns) {
            Menu::query()->where('pid', $id)->delete();
            Menu::query()->insert(array_map(function ($v) use ($id) {
                $v['pid'] = $id;
                $v['type'] = 3;
                return $v;
            }, $btns));
        }
    }

    protected function checkParams(&$params): void
    {
        if ($params['pid'] > 0) {
            $pMenu = Menu::query()->find($params['pid'])->toArray();
            $params['pre_path'] = $pMenu['pre_path'] . $pMenu['path'] . ($pMenu['path'] === '/' ? '' : '/');
            $params['path'] = ltrim($params['path'], '/');
        }
    }


}
